import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { FormControl } from '@angular/forms';


import { Post } from '../model/post-model';
import { PostService } from './services/post.list.service';



@Component({
    selector:'app-postlist',
    templateUrl:'./post.component.html',
    styleUrls:['./post.component.css'],
    providers:[
        PostService
    ]
})
export class PostComponent implements OnInit{
    public maxSize:number = 5;
    public itemsPerPage:number = 5;
    public totalItems : number;

	public currentPage:number = 1;
    public numPages;
    public searchText:string;
    public searchTextStream:Subject<string> = new Subject();

    public postList:Array<Post>;
    constructor(
        public router:Router,
        public activateRoute : ActivatedRoute,
        public postService : PostService,

    ){}

    ngOnInit(){

        this.activateRoute.params.subscribe( params => {
            console.log(params);
            this.loadData(this.searchText,this.currentPage);
        })

        this.searchTextStream
	        .debounceTime(500)
	        .distinctUntilChanged()
	        .subscribe(searchText => {
				console.log(this.searchText);
	        	this.loadData(this.searchText,this.currentPage)
	        });
    }
    public loadData(searchText:string,page:number){
		let offset = (this.currentPage-1)*this.itemsPerPage;
		let end = (this.currentPage)*this.itemsPerPage;

		return this.postService.getPostList(searchText,page).subscribe(
			res=>{
				this.totalItems = res["total"];
				//TODO.正式环境中，需要去掉slice
				this.postList = res["items"].slice(offset,end>this.totalItems?this.totalItems:end);
			},
			error => {console.log(error)},
			() => {}
		);
	}
	
	public pageChanged(event:any):void {
		this.router.navigateByUrl("posts/page/"+event.page);
	}

	public searchChanged($event):void{
		this.searchTextStream.next(this.searchText);
	}

	public gotoWrite():void{
		//TODO：如果没有登录，跳转到登录页，如果已登录，跳往写作页
		this.router.navigateByUrl("user/write");
	}
}

